<!--
 * @Author: 橘子
 * @Date: 2022-11-26 09:33:29
 * @Project_description: demo
 * @Description: 代码是我抄的，不会也是真的
-->
<template>
  <div>
    <el-card class='box-card' shadow='always'>
      <div slot='header' class='clearfix'>
        <span>修改密码</span>
      </div>
      <!-- 内容 -->
      <el-form ref='form' :model='form' :rules='rules' class='demo-ruleForm' label-width='100px' status-icon>
        <el-form-item label='旧密码' prop='oldPassword'>
          <el-input v-model='form.oldPassword' autocomplete='off' type='password'></el-input>
        </el-form-item>
        <el-form-item label='新密码' prop='newPassword'>
          <el-input v-model='form.newPassword' autocomplete='off' type='password'></el-input>
        </el-form-item>
        <el-form-item label='确认新密码' prop='checkNewPassword'>
          <el-input v-model='form.checkNewPassword' autocomplete='off' type='password'></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type='primary' @click='submitForm()'>提交</el-button>
          <el-button @click='resetForm()'>重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'password',
  // import引入的组件需要注入到对象中才能使用
  components: {},
  data() {
    var checkNewPasswordvalidator = (rule, value, callback) => {
      if (this.form.oldPassword == value) {
        callback(new Error('密码无修改'))

      } else if (this.form.newPassword !== value) {
        callback(new Error('两次密码不一致'))

      } else {
        callback()
      }
    }
    // 这里存放数据
    return {
      form: {
        id: '',
        oldPassword: '',
        newPassword: '',
        checkNewPassword: '',
      },
      rules: {
        oldPassword: [{ required: true, message: '旧密码不能为空', trigger: 'blur' }],
        newPassword: [{ required: true, message: '新密码不能为空', trigger: 'blur' }],
        checkNewPassword: [
          { required: true, message: '新密码不能为空', trigger: 'blur' },
          { validator: checkNewPasswordvalidator, trigger: 'blur' },
        ],
      },
    }
  },
  // 监听属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {},
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.form.userId = this.$db._getUser('userId')
  },
  // 方法集合
  methods: {
    submitForm() {
      let _this = this
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          await _this.$api.user.put({
            userId: this.form.userId,
            password: this.form.newPassword,
          })
          _this.$message.success('更新成功')
          // 清除
          _this.$db._clearUser()
          _this.$router.push('/login')
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm() {
      this.$refs.form.resetFields()
    },
  },
}
</script>

<style lang='scss' scoped>
//@import url(); 引入公共css类
</style>
